package com.axdac.mixbind.sql.db;

import android.database.Cursor;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/4/4 0004.
 */

public class ORMUtil {
    public static List<Object> bindObject(Cursor cursor,String entity){
        List<Object> array = new ArrayList<Object>();
        try {
            if (cursor.moveToFirst() == false) {
                return array;
            }
            for (int i = 0; i < cursor.getCount(); i++) {
                Object object = Class.forName(entity).newInstance();
                Field[] fields = object.getClass().getFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    if (field.isAnnotationPresent(Column.class)) {
                        Column column = field.getAnnotation(Column.class);
                        String name = "";
                        if(column.tableName().equals("")){
                            name = column.columnName();
                        }else{
                            name = column.tableName()+"."+column.columnName();
                        }
                        int index = cursor.getColumnIndex(name);
                        if (index != -1) {
                            String value = cursor.getString(index);
                            field.set(object, value);
                        }
                    }
                }
                array.add(object);
                cursor.moveToNext();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return array;
    }
}
